package audi.a4.control.gui;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;

import audi.a4.control.core.AbstractAudiA4Packet;
import audi.a4.control.core.AudiA4CanCode;
import audi.a4.control.core.AudiA4PacketFactory;
import audi.a4.control.core.FileSelectionFactory;
import audi.a4.control.core.TrcFilter;

import net.miginfocom.swing.MigLayout;

public class ContentPanel extends JPanel {

	/**
	 * long 
	 */
	private static final long serialVersionUID = -6327924777120624731L;
	
	private ArrayList<OverlayWidget> olw = new ArrayList<OverlayWidget>();
	private ArrayList<CanBusCodeWidget> cbcw = new ArrayList<CanBusCodeWidget>();
	
	private JButton loadFile = new JButton("Load Trace File");
	private File trace = null;
	private JPanel input = new JPanel(new MigLayout());
	private JPanel overlays = new JPanel(new MigLayout());
	private JPanel cancodes = new JPanel(new MigLayout());
	private CanCodePanel canScroll = new CanCodePanel(cancodes);
	public ContentPanel() {
		setLayout(new MigLayout());
		
//		JButton b = new JButton("Button!!");
//		b.addActionListener(new ActionListener() {
//			
//			@Override
//			public void actionPerformed(ActionEvent arg0) {
//				System.out.println("Click!!");
//			}
//		});
//		
//		add(new JLabel("Element 1"), "wrap");
//		add(b, "wrap");
		
		
		loadFile.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent arg0) {
				trace = FileSelectionFactory.GetFile(null, new TrcFilter());
				if(trace != null) {
					try {
						runTraceDump(new FileInputStream(trace), false);
					} catch (FileNotFoundException e) {
						e.printStackTrace();
					}
				}
			}
		});
		input.add(loadFile);

		input.setBorder(BorderFactory.createLoweredBevelBorder());
		add(input, "wrap");
		add(overlays, "wrap");
		add(canScroll, "wrap");
		addOverlayGraph();
	}
	private void addOverlayGraph() {
		OverlayWidget w = new OverlayWidget();
		olw.add(w);
		overlays.add(w);
	}
	private void addWidget(CanBusCodeWidget w) {
		cbcw.add(w);
		cancodes.add(w,"wrap");
		for(OverlayWidget ol: olw) {
			ol.setWidgets(cbcw);
		}
	}
	protected void fireDataUpdate() {
		cancodes.setBorder(BorderFactory.createLoweredBevelBorder());
		overlays.setBorder(BorderFactory.createLoweredBevelBorder());
		canScroll.updateScroller(720,380);
	}
	private void runTraceDump(final InputStream stream, final boolean keepRinning) {
		new Thread() {
			public void run() {
				try{
				  // Open the file that is the first 
				  // command line parameter
				  // Get the object of DataInputStream
				  DataInputStream in = new DataInputStream(stream);
				  BufferedReader br = new BufferedReader(new InputStreamReader(in));
				  String strLine;
				  //Read File Line By Line
				  double timeTotal=0;
				  double timeLast=0;
				  while ((strLine = br.readLine()) != null || keepRinning )   {
					  if(strLine != null) {
						  String [] splits = strLine.split("\\ ");
						  ArrayList<String> data = new ArrayList<String>();
						  double t = Double.parseDouble(splits[0]);
						  if(((t+50)<timeLast)) {
							  timeTotal +=60;  
						  }
						  timeLast = t;
						  double currentTime = timeTotal +t;
						  String opcode = splits[1];
						  for(int i=3;i<splits.length;i++) {
							  if(!splits[i].equals("")) {
								  data.add(splits[i]);
							  }
						  }
						  data.remove(0);//Remove the Data length 
						  //
						  int ID =Integer.parseInt(opcode, 16);
						  AudiA4CanCode code  = AudiA4CanCode.get(ID);
						  AbstractAudiA4Packet packet = AudiA4PacketFactory.getPacket(	currentTime,
								  														code,
								  														ID,
								  														data); 
//						  if(code == AudiA4CanCode.ECU_1) {
//							  System.out.println("Time="+currentTime+" Clipped="+t+" Total="+timeTotal+" Data="+data+" Packet="+packet);
							  boolean exists = false;
							  for(CanBusCodeWidget w:cbcw) {
								  if(w.getCanCodeNumber() == packet.getCanCodeNumber()) {
									  w.addPacket(packet);
									  exists = true;
								  }
							  }
							  if(!exists) {
								  System.out.println("Adding control widget: "+packet.getAudiA4CanCode());
								  CanBusCodeWidget w = new CanBusCodeWidget(packet.getAudiA4CanCode(),ID);
								  w.addPacket(packet);
								  addWidget(w);
							  }
							  fireDataUpdate();
//						  }
					  }
				  }
				  //Close the input stream
				  in.close();
			    }catch (Exception e){//Catch exception if any
			    	e.printStackTrace();
			    	System.err.println("Error: " + e.getMessage());
			    }
			}
		}.start();
	}

}
